package com.lbb.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 服务端请求处理线程 
 * 
 * 每一个请求由一个线程单独处理
 * @author admin
 *
 */
public class RequestHandler implements  Runnable{
	
	private Socket request;
	
	
	Logger log = LoggerFactory.getLogger(RequestHandler.class);
	
	
	public RequestHandler(Socket request){
		
		this.request=request;
	}

	
	public void run() {
		
		try {
			String key = readClient(request.getInputStream());
			Thread.sleep(10000);
			
			request.shutdownInput();
			
			String token = getToken(key);
			OutputStream os = request.getOutputStream();
			os.write(token.getBytes());
			os.flush();
			request.shutdownOutput();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 读取客户端文本信息
	 * @param request
	 * @return
	 * @throws IOException
	 */
	private String readClient(InputStream in) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		
		String line = "";
		StringBuffer  sb = new StringBuffer();
				
		while ((line = br.readLine() )!= null){
			sb.append(line);
		}
		
		log.debug("客户端发来信息：{},线程 {}处理", sb.toString(),Thread.currentThread().getName());
		return sb.toString();
	}
	
	
	private String getToken(String key){
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		return key +"@" +uuid;
	}
	

}
